<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房间号" prop="roomNumber">
        <el-input v-model="queryParams.roomNumber" placeholder="请输入房间号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="房间名称" prop="roomName">
        <el-input v-model="queryParams.roomName" placeholder="请输入房间名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
              <el-form-item label="房间类型" prop="valueRoomType">
          <template >
            <el-select v-model="queryParams.roomTypeId" clearable placeholder="请选择房间类型">
              <el-option v-for="item in optionsRoomType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

          </template>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['data:room:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['data:room:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['data:room:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['data:room:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房间ID" align="center" prop="roomId" />
      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="房间名称" align="center" prop="roomName" />
      <el-table-column label="房间类型" align="center" prop="roomTypeId" >
                  <template slot-scope="scope">
          <span v-text="roomTypeParse(scope.row.roomTypeId)"></span>
        </template>
      </el-table-column>
            <el-table-column label="所属楼层" align="center" prop="floorId" >
                  <template slot-scope="scope">
          <span v-text="floorParse(scope.row.floorId)"></span>
        </template>
      </el-table-column>
      <el-table-column label="房间价格" align="center" prop="roomPrice" />
      <el-table-column label="折后价" align="center" prop="roomDiscountPrice" />
      <el-table-column label="床型" align="center" prop="bedType" />
      <el-table-column label="宽带" align="center" prop="internet" />
     
      
            <el-table-column label="房间描述" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text"  @click="openDescription(scope.row)" v-hasPermi="['data:room:edit']">详情</el-button>
        </template>
      </el-table-column>
            <el-table-column label="图片封面"   align="center" prop="imageUrl">
        <template v-slot:default="scope">

          <el-image :src="scope.row.imageUrl">
          </el-image>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['data:room:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['data:room:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改房间对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body @close="offDialog" :show-close='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="房间类型" prop="valueRoomType" class="valueRoomTypeStyle">
          <template >
            <el-select v-model="valueRoomType" clearable placeholder="请选择房间类型">
              <el-option v-for="item in optionsRoomType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

          </template>
        </el-form-item>
        <el-form-item label="所属楼层" prop="valueFloor" class="valueRoomTypeStyle">
          <template>
            <el-select v-model="valueFloor" clearable placeholder="请选择所属楼层">
              <el-option v-for="item in optionsFloor" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

          </template>
        </el-form-item>
        <el-form-item label="房间价格" prop="roomPrice">
          <el-input v-model.number="form.roomPrice" placeholder="请输入房间价格" />
        </el-form-item>
        <el-form-item label="折后价" prop="roomDiscountPrice">
          <el-input v-model.number="form.roomDiscountPrice" placeholder="请输入折后价" />
        </el-form-item>
        <el-form-item label="宽带" prop="internet">
          <el-input v-model="form.internet" placeholder="宽带情况" />
        </el-form-item>

        <el-form-item label="床型" prop="bedType">
          <el-input v-model="form.bedType" placeholder="请输入内容" />
        </el-form-item>
        <!--:action里面放图片上传调取的后台方法 :headers设置上传的请求头部,使请求携带自定义token，获取访问权限 -->
        <!--:on-success图片上传成功后的回调方法，用于拿到图片存储路径等信息-->
        <!--:before-upload图片上传前的逻辑判断，例如判断图片大小，格式等-->
        <!--:on-preview图片预览方法 :on-remove图片删除方法 list-type代表文件列表的类型 -->
        <!--file-list存放成功上传图片列表，这里此属性用于修改功能时页面已有图片的显示-->

        <el-form-item label="图片封面" prop="imageUrl" label-width="40" style="margin-left: 11px;">
          <el-upload :action="imgUpload.url" :headers="imgUpload.headers" list-type="picture-card" :limit="limit" :on-exceed="handleExceed" :on-success="handlePictureSuccess" :before-upload="beforeAvatarUpload" :on-preview="handlePictureCardPreview" :on-remove="removeImg" :file-list="fileList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" v-if="form.imageUrl" :src="form.imageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="房间描述" prop="roomDescription">
          
          <WangEditor  v-model="form.roomDescription"  v-if="isShowWangEditor" ref="wangEditor"></WangEditor>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 房间详情的dialog -->
    <el-dialog
  title="房间详情"
  :visible.sync="dialogVisibleRoomDescription
"
:fullscreen='true'
:destroy-on-close = 'true'
>
  <span v-html='descriptionDialog'></span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleRoomDescription = false">关 闭</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom, delFile } from '@/api/data/room'
//导入房间类型api
import { getAllRoomType } from '@/api/data/roomType'
//获取楼层api
import { listGetAll } from '@/api/data/floor'
//引入token
import { getToken } from '@/utils/auth'

export default {
  name: 'Room',
  data() {
    // 自定义表单验证
    //验证房间号房间号不能超过50位，非空
    var checkRoomNumber = (rule, value, callback) => {
      setTimeout(() => {
        let reg = /^.{1,50}$/
        if (!reg.test(value)) {
          callback(new Error('房间号不能超过50位'))
        } else {
          callback()
        }
      }, 1000)
    }
    //验证房间名称不能超过50位
    var checkRoomName = (rule, value, callback) => {
      setTimeout(() => {
        let reg = /^.{1,50}$/
        if (!reg.test(value)) {
          callback(new Error('房间名称不能超过50位'))
        } else {
          callback()
        }
      }, 1000)
    }
    //验证床型不能超过50位
    var checkbedType = (rule, value, callback) => {
      setTimeout(() => {
        let reg = /^.{1,50}$/
        if (!reg.test(value)) {
          callback(new Error('床型不能超过50位'))
        } else {
          callback()
        }
      }, 1000)
    }

    //验证折扣价，折扣价不能小于原价
    var checkRoomDiscountPrice = (rule, value, callback) => {
      setTimeout(() => {
        if (value >= this.form.roomPrice) {
          callback(new Error('折扣价不能小于等于原价'))
        } else {
          callback()
        }
      }, 500)
    }
    return {
      // 详情内容dialog
      descriptionDialog:'',
      // 房间详情
      dialogVisibleRoomDescription: false,
      // wangEditor的组件销毁和恢复
      isShowWangEditor:false,
      // 图片上传参数
      // 图片数量限制
      limit: 1,
      //页面上存的暂时图片地址List
      fileList: [{ url: '' }],
      //图片地址
      imageUrl: '',
      dialogVisible: false,
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + '/file/upload'
      },
      //房间类型参数
      optionsRoomType: [],
      valueRoomType: '',
      roomType:[],
      //楼层参数
      optionsFloor: [],
      valueFloor: '',
      floor:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间表格数据
      roomList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomNumber: null,
        roomName: null,
        floorId: null,
        roomTypeId: null,
        roomPrice: null,
        roomDiscountPrice: null,
        bedType: null,
        internet: null,
        roomDescription: null,
        imageUrl: null
      },
      // 表单参数
      form: {
      
      },
      // 表单校验
      rules: {
        roomNumber: [
          { required: true, message: '房间号不能为空', trigger: 'blur' },
          { validator: checkRoomNumber, trigger: 'blur' }
        ],
        roomName: [
          { required: true, message: '房间名称不能为空', trigger: 'blur' },
          { validator: checkRoomName, trigger: 'blur' }
        ],
        bedType: [
          { required: true, message: '床型不能为空', trigger: 'blur' },
          { validator: checkbedType, trigger: 'blur' }
        ],
        roomPrice: [
          { required: true, message: '房间价格不能为空' },
          { type: 'number', message: '必须为数字值' }
        ],
        roomDiscountPrice: [
          { required: true, message: '折扣价不能为空' },
          { type: 'number', message: '年龄必须为数字值' },
          { validator: checkRoomDiscountPrice, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    getAllRoomType().then(response=>{
      this.roomType = response.data
    })
    listGetAll().then(response=>{
      this.floor = response.data
    })
    this.getList()
     //调用获取房间类型的接口
      this.getAllRoomTypeList()
  },
  methods: {
    // 处理表格的所属楼层
    floorParse(floorId){
      var floorNick = null;
      this.floor.forEach((value)=>{
        if(value.floorNumber == floorId){
          return floorNick = value.floorName
        }
      })
      return floorNick
    },
    // 处理表格的房间类型
    roomTypeParse(roomTypeId){
      var roomTypeNick = null;
      this.roomType.forEach((value)=>{
        if(value.roomTypeId == roomTypeId){
          return roomTypeNick = value.roomTypeName
        }
      })
      return roomTypeNick
    },
          // 房间描述打开
      openDescription(data) {
        this.dialogVisibleRoomDescription = true
        this.descriptionDialog = data.roomDescription
      },
    //模态框关闭执行
    offDialog() {
      // 销毁wangEditor
      this.isShowWangEditor = false
      this.reset()
    },
    /** 查询房间列表 */
    getList() {
      this.loading = true
      listRoom(this.queryParams).then(response => {
        this.roomList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        roomId: null,
        roomNumber: null,
        roomName: null,
        floorId: null,
        roomTypeId: null,
        roomPrice: null,
        roomDiscountPrice:null,
        bedType: null,
        internet: null,
        roomDescription: null,
        imageUrl: null,
        createTime: null
      }
      // 房间类型参数
      this.optionsRoomType = []
      this.valueRoomType = ''
      //  楼层参数
      this.optionsFloor = []
      this.valueFloor = ''
      // 文件清空
      this.fileList = []
      // 把头像地址清空
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roomId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 将wangeditor恢复
      this.isShowWangEditor = true
      this.reset()
      this.open = true
      this.title = '添加房间'
      //调用获取房间类型的接口
      this.getAllRoomTypeList()
      //调用获取楼层的接口
      this.getAllFloorList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
       //创建wangEditor组件
      this.isShowWangEditor = true
      this.reset()
      //调用获取房间类型的接口
      this.getAllRoomTypeList()
      //调用获取楼层的接口
      this.getAllFloorList()
      const roomId = row.roomId || this.ids
      getRoom(roomId).then(response => {
        this.form = response.data
                // 图片回显赋值
        this.fileList = [{ url:  this.form.imageUrl }]
        //加个延迟，防止数据无法显示出来，由于页面加载太快
        setTimeout(
          () => {
            // 给 this.valueRoomType赋值回显
            this.optionsRoomType.forEach(list => {
              if (list.value == this.form.roomTypeId) {
                this.valueRoomType = this.form.roomTypeId
              }
            })
            // 给 this.valueFloor赋值回显
            this.optionsFloor.forEach(list => {
              if (list.value == this.form.floorId) {
                this.valueFloor = this.form.floorId
              }
            })
          },

          10
        )

        this.open = true
        this.title = '修改房间'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.roomId != null) {
            // 给楼层id，房间类型id赋值
            this.form.floorId = this.valueFloor
            this.form.roomTypeId = this.valueRoomType
            updateRoom(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // 给楼层id，房间类型id赋值
            this.form.floorId = this.valueFloor
            this.form.roomTypeId = this.valueRoomType
            addRoom(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roomIds = row.roomId || this.ids
      this.$modal
        .confirm('是否确认删除房间编号为"' + roomIds + '"的数据项？')
        .then(function () {
          return delRoom(roomIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'data/room/export',
        {
          ...this.queryParams
        },
        `room_${new Date().getTime()}.xlsx`
      )
    },
    // 获取所有房间类型
    getAllRoomTypeList() {
      var _this = this
      getAllRoomType().then(response => {
        // 循环每一条数据将他们的房间类型id和房间名称取出来组成一个对象赋值到optionsRoomType中
        response.data.forEach(function (value) {
          //定义一个对象
          var roomType = {}
          roomType.value = value.roomTypeId
          roomType.label = value.roomTypeName
          _this.optionsRoomType.push(roomType)
        })
      })
    },
    //获取所有楼层列表
    getAllFloorList() {
      var _this = this
      listGetAll().then(response => {
        // 循环每一条数据将他们的楼层id和楼层名称取出来组成一个对象赋值到options中
        response.data.forEach(function (value) {
          //定义一个对象
          var floor = {}
          floor.value = value.floorNumber
          floor.label = value.floorName
          _this.optionsFloor.push(floor)
        })
      })
    },
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type == 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        
      }
      return isJPG && isLt2M
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.form.imageUrl = file.url
      this.dialogVisible = true
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径
      this.form.imageUrl = file.response.msg// 注：重要(用于添加到数据库)
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`)
    },
    //删除酒店封面
    removeImg() {
      // 发起请求把图片名传到后台
      delFile(this.form.imageUrl)
      this.form.imageUrl = null;
    },
   
  }
}
</script>


<style scoped>
.valueRoomTypeStyle{
  position: relative;
}
.valueRoomTypeStyle:before{
         content: "*";
    color: #ff4949;
    position: absolute;
    /* left: 50%; */
    top: 50%;
    /* -webkit-transform: translate(-50%, -50%); */
    transform: translate(-50%, -50%);
}
</style>
